package com.xs.shop.orders.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.Result;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.goods.feign.api.GoodsClient;
import com.xs.shop.goods.model.vo.GoodsListDetailsVO;
import com.xs.shop.orders.model.entity.Cart;
import com.xs.shop.orders.model.entity.OrderItem;
import com.xs.shop.orders.service.mapper.OrderItemMapper;
import com.xs.shop.orders.service.service.OrderItemService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  订单项服务实现类
 * </p>
 *
 * @author xs,zyx
 * @since 2025-07-22
 */
@Slf4j
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {

    @Resource
    private GoodsClient goodsClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BigDecimal addOrderItem(List<Cart> cartItems) {
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        List<Long> goodsIds = new ArrayList<>();

        Map<Long, Cart> cartMap = new HashMap<>();
        for(Cart cartItem : cartItems){
            Long goodsId = cartItem.getGoodsId();
            goodsIds.add(goodsId);
            cartMap.put(goodsId, cartItem);
        }
        Result<List<GoodsListDetailsVO>> goodsListDetailByIds = goodsClient.findGoodsListDetailByIds(goodsIds);
        log.info("调用商品服务结果: {}", goodsListDetailByIds);
//      List<GoodsListDetailsVO> goodsListDetails = goodsListDetailByIds.getData();
        // 安全获取数据，防止空指针
        List<GoodsListDetailsVO> goodsListDetails = Optional.ofNullable(goodsListDetailByIds)
                .map(Result::getData)
                .orElse(Collections.emptyList());

        // 如果没有商品数据，记录日志并返回空列表
        if (goodsListDetails.isEmpty()) {
            log.warn("未查询到任何商品详情");
            return BigDecimal.ZERO;
        }
        BigDecimal totalAmount = new BigDecimal("0");

        for (GoodsListDetailsVO goodsListDetail : goodsListDetails) {
            log.info("goodsListDetail:{}", goodsListDetail);

            // 从购物车中获取该商品的数量
            Cart cartItem = cartMap.get(goodsListDetail.getId());
            if (cartItem == null) {
                log.warn("商品ID:{}在购物车中未找到", goodsListDetail.getId());
                continue;
            }

            Integer quantity = cartItem.getQuantity();

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(cartItems.get(0).getId());  // getFirst()用不了啊~ QwQ
            orderItem.setGoodsId(goodsListDetail.getId());
            orderItem.setGoodsName(goodsListDetail.getName());
            orderItem.setGoodsPrice(goodsListDetail.getPrice());
            orderItem.setGoodsImage(goodsListDetail.getImageUrl());
            // 设置购买数量
            orderItem.setQuantity(quantity);
            // 计算单品总价 = 单价 × 数量
            BigDecimal itemTotalAmount = goodsListDetail.getPrice().multiply(new BigDecimal(quantity));
            orderItem.setTotalAmount(itemTotalAmount);
            // 累加到订单总金额
            totalAmount = totalAmount.add(itemTotalAmount);
            orderItems.add(orderItem);
        }
        
        this.saveBatch(orderItems);

        return totalAmount;
    }

    @Override
    public OrderItem addOrderItem(OrderItem orderItem) {
        this.save(orderItem);
        return orderItem;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteOrderItem(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }
//
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderItem updateOrderItem(OrderItem orderItem) {
        if (orderItem == null || orderItem.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        orderItem.setUpdatedAt(new Date());
        this.updateById(orderItem);
        return orderItem;
    }
//
    @Override
    public OrderItem getOrderItemById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }
//
    @Override
    public List<OrderItem> getOrderItemsByOrderId(Long orderId) {
        if (orderId == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }

        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId)
                  .eq(OrderItem::getIsDeleted, 0);
        return this.list(queryWrapper);
    }
}
